package com.zixun.service.Impl;

import com.zixun.model.User;
import com.zixun.repository.UserRepository;
import com.zixun.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.*;

/**
 * Created by Basil on 16/8/13.
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserRepository userRepository;


    @Override
    public Page<User> findAllByIsExpert(final Integer isExpert, Integer pageIndex, Integer countPerPage) {
        Specification<User> specification = new Specification<User>() {
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Path<Integer> $isExpert = root.get("isExpert");
                Predicate _isExpert = cb.equal($isExpert, isExpert);
                return cb.and(_isExpert);
            }
        };
        Pageable pageable = new PageRequest(pageIndex - 1, countPerPage);
        return userRepository.findAll(specification, pageable);
    }

    @Override
    public boolean isUserExist(Integer userId) {
        if(userRepository.findById(Integer.valueOf(userId))==null){
            return false;
        }else {
            return true;
        }
    }

    @Override
    public User getUserByUserId(Integer userId) {
        return userRepository.findById(Integer.valueOf(userId));
    }
}
